﻿using EasyClassUI.forms.blog;
using Markdig;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EasyClassUI.entity;
using EasyClassUI.WebRequest;

namespace EasyClassUI.forms.group
{
    public partial class blogDetailShow : Form
    {
        private Post post;
        public blogDetailShow(Post post)
        {
            this.post = post;
            InitializeComponent();
            likeCount.Text = post.LikeCount.ToString();
            if (post.Comments == null) {
                CommentCount.Text = "0";
            }
            else CommentCount.Text = post.Comments.Count.ToString();
            initBlogComment();
            initBlogAppendice();
            initBlogContent();
            //this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.RenewLike);
        }

        public void DisplayComments(Comment comment) {
            blogCommentCell bcc = new blogCommentCell(comment.Publisher, comment.Body);
            commentPanel.Controls.Add(bcc);
        }

        public void addComment(string body) {
            string publisher = User.CurrentUser.UserAccount;
            blogCommentCell bcc = new blogCommentCell(publisher, body);
            commentPanel.Controls.Add(bcc);
            CommentCount.Text = (int.Parse(CommentCount.Text) + 1).ToString();
        }

        public void DisplayResources(StudyResource resource) {
            BlogAppendice ba = new BlogAppendice(resource.FileName, (resource.FileSize / 1024).ToString(), post);
            appendicePanel.Controls.Add(ba);
        }

        public void initBlogComment()
        {
            // 初始化评论列表
            if (post.Comments == null) {
                return;
            }
            Parallel.ForEach(post.Comments, c => DisplayComments(c));
        }

        public void initBlogAppendice()
        {
            // 初始化附件列表
            if (post.StudyResources == null) {
                return;
            }
            Parallel.ForEach(post.StudyResources, r => DisplayResources(r));
        }
        /// <summary>
        /// 读取文件，返回相应字符串
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <returns>返回文件内容</returns>
        private string ReadFile(string fileName)
        {
            StringBuilder str = new StringBuilder();
            using (FileStream fs = File.OpenRead(fileName))
            {
                long left = fs.Length;
                int maxLength = 100;//每次读取的最大长度
                int start = 0;//起始位置
                int num = 0;//已读取长度
                while (left > 0)
                {
                    byte[] buffer = new byte[maxLength];//缓存读取结果
                    char[] cbuffer = new char[maxLength];
                    fs.Position = start;//读取开始的位置
                    num = 0;
                    if (left < maxLength)
                    {
                        num = fs.Read(buffer, 0, Convert.ToInt32(left));
                    }
                    else
                    {
                        num = fs.Read(buffer, 0, maxLength);
                    }
                    if (num == 0)
                    {
                        break;
                    }
                    start += num;
                    left -= num;
                    str = str.Append(Encoding.UTF8.GetString(buffer));
                }
            }
            return str.ToString();
        }
        //读取markdown并显示
        public void initBlogContent()
        {
            string str = ReadFile($"./posts/{post.PostID}.md");
            String headHtml = "<!doctype html><html><head><meta http-equiv=\"content-type\" Content=\"text/html;charset=utf-8\"/><style>body{font-family:\"Microsoft Yahei\";}</style></head><body>";
            String content = Markdown.ToHtml(str);
            String endHtml = "</body></html>";
            webBrowser1.DocumentText = headHtml + content + endHtml;
        }
        private void returnButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void viewedCount_Click(object sender, EventArgs e)
        {

        }

        private void commentPanel_Paint(object sender, PaintEventArgs e)
        {

        }

        private void blogDetailShow_Load(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void appendicePanel_Paint(object sender, PaintEventArgs e)
        {

        }

        bool ifLiked = false;

        private void likePictureBox_Click(object sender, EventArgs e)
        {
            ifLiked = !ifLiked;
            if (ifLiked) {
                likePictureBox.Image = Properties.Resources.like;
                likeCount.Text = (int.Parse(likeCount.Text) + 1).ToString();                
            }
            else {
                likePictureBox.Image = Properties.Resources.like_default;
                likeCount.Text = (int.Parse(likeCount.Text) - 1).ToString();
            }
        }

        private void likeCount_Click(object sender, EventArgs e)
        {

        }

        private void RenewLike() {
            PostService postService = new PostService();
            if (post.LookCount < int.Parse(likeCount.Text)) {
                postService.LikePost(post.PostID.ToString());
            }
        }

        private void commentPictureBox_Click(object sender, EventArgs e)
        {
            addCommentForm acf = new addCommentForm(post);
            acf.Show(this);
        }

        private void blogDetailShow_FormClosing(object sender, FormClosingEventArgs e) {
            RenewLike();
            groupUC.groupView.showNewestBlogs();
        }
    }
}
